﻿using OperationPlugins.Applications.Models;
using System;

namespace OperationPlugins.Applications
{
    /// <summary>
    /// This is the default IApplicationInstance implementation.
    /// </summary>
    internal sealed class ApplicationInstanceImpl : IApplicationInstance
    {
        /// <summary>
        /// The application request context.
        /// </summary>
        internal ApplicationRequestContext Context { get; private set; }

        /// <summary>
        /// Defines an application instance.
        /// </summary>
        internal AppInstance App { get; private set; }

        /// <summary>
        /// The sandbox.
        /// </summary>
        internal Sandbox Sandbox { get; set; }

        /// <summary>
        /// Initializes a new instance of the DefaultApplicationInstance class.
        /// </summary>
        /// <param name="context">The application request context.</param>
        /// <param name="app">The application definition.</param>
        internal ApplicationInstanceImpl(ApplicationRequestContext context, AppInstance app)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (app == null)
            {
                throw new ArgumentNullException("app");
            }

            Context = context;
            App = app;
        }

        /// <summary>
        /// Proceeds a login.
        /// </summary>
        /// <exception cref="ApplicationInstanceException">If the login fails.</exception>
        public void Login()
        {
            if (Account.IsAuthorized(Context.Headers.Username, Context.Headers.Password, App) == false)
            {
                throw new ApplicationInstanceException("Unauthorized");
            }
        }

        /// <summary>
        /// Creates a new IValidatorProxy.
        /// </summary>
        /// <returns>IValidatorProxy.</returns>
        public IValidatorProxy CreateValidator()
        {
            return new ValidatorProxyImpl(this);
        }

        public void Dispose()
        {
        }

    }
}